﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using SoftwareConsulting.BI11.Studio.Core.DBProviders;
using SoftwareConsulting.BI11.Studio.Core.Project.Metadata;
using SoftwareConsulting.BI11.Studio.InternalServices;
using SoftwareConsulting.BI11.Studio.UI.Properties;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Extensions;
using SoftwareConsulting.BI11.Controls.Metadata;

namespace SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Tables
{
    public partial class TableViewerDialog : RestorableForm
    {
        private bool _noDirtyFlag; //флаг отключения метки проекта как измененного
        private ITable _currentTable;        
        private object _preValue;
        private bool _programChange;

        public TableViewerDialog(ITable table)
        {            
            _currentTable = table;
            InitializeComponent();
        }

        /// <summary>
        /// Инициализация окна
        /// </summary>
        private void Initialize()
        {
            this.SetObjectViewerCaption(Resources.BI_PROJECTEXPLORER_TABLEVIEWER_CAPTION, _currentTable);
            this.Icon = MetadataObjectKind.Table.GetIcon();
            _programChange = false;
            _noDirtyFlag = true;            
            TableDataGrid.Rows.Clear();
            TableDataGrid.Columns.Clear();
            _currentTable.ConnectDataGrid(TableDataGrid);
            ICollection<string> colNames = _currentTable.GetColumnNames();
            foreach(string cname in colNames)
            {                
                for (int j = 0; j < TableDataGrid.Rows.Count; j++)
                {
                    if (_currentTable.GetColumnProperties(cname).ToAutoInc)
                    {
                        TableDataGrid.Rows[j].Cells[TableDataGrid.Columns[cname].Index].ReadOnly = true;
                    }
                }
            }            
            _noDirtyFlag = false;
        }

        private void DataRedactorForm_Load(object sender, EventArgs e)
        {
            Initialize();
        }

        private bool checkOnKeyUnique(int rowId, int columnId)
        {
            for (int i = 0; i < TableDataGrid.Rows.Count; i++)
            {
                if ((i != rowId) && (TableDataGrid.Rows[i].Cells[columnId] == TableDataGrid.Rows[rowId].Cells[columnId]))
                {
                    return false;
                }
            }
            return true;
        }

        private void TableDataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (_programChange)
                return;
            string cname = TableDataGrid.Columns[e.ColumnIndex].Name;
            DataColumnProperties props = _currentTable.GetColumnProperties(cname);
            bool isCorrectData = true;
            DataGridViewCell cell = TableDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
            string str = cell.Value.ToString();
            switch (props.ColumnType.ToString())
            {
                case "System.Int32":
                    int ival = -1;
                    isCorrectData = int.TryParse(str, out ival);
                    break;
                case "System.Boolean":
                    //не рассматривается, т.к. задается все равно
                    //чекбоксом, а не строкой
                    break;
                case "System.Double":
                    double dval = -1.0;
                    isCorrectData = double.TryParse(str, NumberStyles.Float, CultureInfo.CurrentCulture, out dval);                    
                    break;
                case "System.DateTime":
                    DateTime dtval = Constants.NullDate;
                    isCorrectData = DateTime.TryParse(str, out dtval);
                    break;
                case "System.String":                    
                    break;
            }       
            if (!isCorrectData)
            {
                _programChange = true;
                cell.Value = _preValue;
                _programChange = false;
                GeneralMethods.ShowUserError(Resources.BI_PROJECTEXPLORER_TABLEVIEWER_INCOMPATIBLETYPES);
                return;
            }
            if (props.IsUniqueValue)
            {
                if (!checkOnKeyUnique(e.RowIndex, e.ColumnIndex))
                {
                    cell.Value = _preValue;
                    GeneralMethods.ShowUserError(Resources.BI_PROJECTEXPLORER_TABLEVIEWER_NONUNIQUETYPES);
                    return;
                }
            }            
            if (cell.Value != _preValue)
            {
                _currentTable.MarkAsJustChanged();                    
            }            
        }

        private void TableDataGrid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            _preValue = TableDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        }
        
        private void OKButton_Click(object sender, EventArgs e)
        {            
            Close();
        }

        private void TableDataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            GeneralMethods.ShowUserError(Resources.BI_PROJECTEXPLORER_TABLEVIEWER_INCORRECTDATA);            
        }

        private void TableDataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (!_noDirtyFlag)
            {
                _currentTable.MarkAsJustChanged();
            }
        }

        private void TableDataGrid_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (!_noDirtyFlag)
            {
                _currentTable.MarkAsJustChanged();
            }
        }

        private void TableViewerDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            OKButton.Focus();//иначе косяки при закрытии формы через крестик (добавляется пустая строка в таблицу)
        }
    }
}
